import 'dart:async';

import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:webview_flutter/webview_flutter.dart';

final currentWebTitleProvider =
    StateProvider.family<String, String>((ref, initTitle) {
  return initTitle;
});

class WebViewPage extends StatefulWidget {
  final String title;
  final String? url;
  final String? content;
  const WebViewPage({required this.title, this.url, this.content, Key? key})
      : super(key: key);
  @override
  WebViewPageState createState() => WebViewPageState();
}

class WebViewPageState extends State<WebViewPage> {
  late final WebViewController _controller;

  int _progressValue = 0;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final bool canGoBack = await _controller.canGoBack();
        if (canGoBack) {
          // 网页可以返回时，优先返回上一页
          await _controller.goBack();
          return Future.value(false);
        }
        return Future.value(true);
      },
      child: Scaffold(
        backgroundColor: const Color(0xffF7F6F9),
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          centerTitle: true,
          leading: IconButton(
            onPressed: () async {
              Navigator.of(context).pop();
            },
            icon: Assets.icons.iconBack.image(width: 18),
            splashRadius: 0.00001,
          ),
          title: Consumer(
            builder: (context, ref, child) {
              return Text(
                ref.watch(currentWebTitleProvider(widget.title)),
                style: const TextStyle(
                  color: Color(0xff333333),
                  fontWeight: FontWeight.normal,
                  fontSize: 18,
                ),
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              );
            },
          ),
        ),
        body: Stack(
          children: [
            WebViewWidget(controller: _controller),
            if (_progressValue != 100)
              LinearProgressIndicator(
                value: _progressValue / 100,
                backgroundColor: Colors.transparent,
                minHeight: 2,
              )
          ],
        ),
      ),
    );
  }

  Uri get initialUrl {
    if (widget.content != null && widget.content!.isNotEmpty) {
      String html = """
   <!DOCTYPE html>
        <html>
        <head><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
          <body>
            ${widget.content!}
            <img src="/obj/static/xitu_juejin_web/e08da34488b114bd4c665ba2fa520a31.svg"/>
          </body>
        </html>
  """;
      return Uri.dataFromString(html, mimeType: 'text/html');
    } else {
      if (widget.url != null) {
        return Uri.parse(widget.url!);
      }

      return Uri.dataFromString('<html><body></body></html>',
          mimeType: 'text/html');
    }
  }

  /// 获取当前加载页面的 title
  _getTitle() async {
    if (widget.title.isEmpty) {}
  }

  @override
  void initState() {
    super.initState();
    // #docregion platform_features
    late final PlatformWebViewControllerCreationParams params;

    params = const PlatformWebViewControllerCreationParams();

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            setState(() {
              _progressValue = progress;
            });
          },
          onPageStarted: (String url) {
            debugPrint('Page started loading: $url');
          },
          onPageFinished: (String url) {
            _getTitle();
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('''
Page resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
          ''');
          },
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
          onUrlChange: (UrlChange change) {
            debugPrint('url change to ${change.url}');
          },
        ),
      )
      ..addJavaScriptChannel(
        'Toaster',
        onMessageReceived: (JavaScriptMessage message) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        },
      )
      ..loadRequest(initialUrl);

    _controller = controller;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(WebViewPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
